<template>
  <div class="container">
    <IconTubiao @satellite="handleSatellite" v-show="!fullscreenShow"></IconTubiao>
    <DownLoadApp v-show="!fullscreenShow"></DownLoadApp>
    <LoginEnter v-show="!fullscreenShow" @selectmap="handleSelectMap"></LoginEnter>
    <SearchLoad
      v-show="!fullscreenShow"
      @inputSearch="handleInputSearch"
      @handleType="handleType"
      @keywordSearch="handleKeywordSearch"
    ></SearchLoad>
    <LocalTemplete
      :localCity="localCity"
      v-show="!fullscreenShow"
      :localLemplete="localLemplete"
    ></LocalTemplete>
    <NavigationRoad @handleGoingTo="handleGoingTo"></NavigationRoad>

    <div class="closefullscreen" :class="{ show: fullscreenShow }">
      <button @click="handleFullscreen">退出全屏</button>
    </div>

    <SearchResult :visible="showSearchItem" :info="itemArr" />
    <div id="panel" :class="{ showpanel: showPanel }"></div>
  </div>
  <div id="panel-driving" :class="{ showpanel: showPanelDriving }"></div>

</template>

<script setup>
import { ref, onMounted } from 'vue'
import IconTubiao from './components/IconTubiao.vue'
import DownLoadApp from './components/DownLoadApp.vue'
import LoginEnter from './components/LoginEnter.vue'
import SearchLoad from './components/SearchLoad.vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import LocalTemplete from './components/LocalTemplete.vue'
import NavigationRoad from './components/NavigationRoad.vue'
import SearchResult from './components/SearchResult.vue'

import useControls from './hooks/useControls.js'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useCounterStore } from './stores/counter.js'
import { storeToRefs } from 'pinia'
const { changeShowPanelDriving,changeShowPanelDrivingTrue,changeShowPanelDrivingFalse, changeShowLogins,changeLogined } = useCounterStore()
const { localCity, cityAdcode,localLemplete,showPanelDriving, showLogins,logined } = storeToRefs(useCounterStore())

const satelliteShow = ref(false) 
const trafficShow = ref(false) 
const mouseToolShow = ref(false) 


const fullscreenShow = ref(false) 

const showSearchItem = ref(false) 
let itemArr = ref([]) 
const showPanel = ref(false) 
const account = ref('') 
const password = ref('') 
let AMap
let map
let mapCenter = ref([]) 
let satellite 
let roadNet
let traffic 
let mouseTool

const handleFullscreen = () => {
  fullscreenShow.value = false
}

const handleSatellite = (index) => {
  if (index === 0) {
    satelliteShow.value = !satelliteShow.value
    if (satelliteShow.value) {
      satellite = new AMap.TileLayer.Satellite()
      roadNet = new AMap.TileLayer.RoadNet()
      map.addLayer(roadNet)
      map.addLayer(satellite)
    } else {
      map.removeLayer(satellite)
      map.removeLayer(roadNet)
    }
  }
  if (index === 1) {
  }
  if (index === 2) {
    trafficShow.value = !trafficShow.value
    if (trafficShow.value) {
      traffic = new AMap.TileLayer.Traffic({
        autoRefresh: true,
        interval: 180,
      })
      map.addLayer(traffic)
    } else {
      map.removeLayer(traffic)
    }
  }
  if (index === 3) {
    mouseToolShow.value = !mouseToolShow.value
    if (mouseToolShow.value) {
      mouseTool = new AMap.MouseTool(map)
      mouseTool.rule({
        startMarkerOptions: {
          icon: new AMap.Icon({
            size: new AMap.Size(19, 31),
            imageSize: new AMap.Size(19, 31),
            image: '//webapi.amap.com/theme/v1.3/markers/b/start.png',
          }),
          offset: new AMap.Pixel(-9, -31),
        },
        endMarkerOptions: {
          icon: new AMap.Icon({
            size: new AMap.Size(19, 31),
            imageSize: new AMap.Size(19, 31),
            image: '//webapi.amap.com/theme/v1.3/markers/b/end.png',
          }),
          offset: new AMap.Pixel(-9, -31),
        },
        midMarkerOptions: {
          icon: new AMap.Icon({
            size: new AMap.Size(19, 31),
            imageSize: new AMap.Size(19, 31),
            image: '//webapi.amap.com/theme/v1.3/markers/b/mid.png',
          }),
          offset: new AMap.Pixel(-9, -31),
        },
        lineOptions: {
          strokeStyle: 'solid',
          strokeColor: '#FF33FF',
          strokeOpacity: 1,
          strokeWeight: 2,
        },
      })
    } else {
      mouseTool.close()
    }
  }
  if (index === 5) {
    fullscreenShow.value = !fullscreenShow.value
  }
}


const handleInputSearch = (keyword) => {
  if (!keyword.trim()) {
    showSearchItem.value = false
    showPanel.value = false
  }
  const autoComplete = new AMap.AutoComplete({
    city: `${cityAdcode.value}`,
    input: 'searchinput',
  })
  const placeSearch = new AMap.PlaceSearch({
    city: `${cityAdcode.value}`,
    map: map,
  })
  autoComplete.on('select', function (e) {
    placeSearch.search(e.poi.name)
    if (e.poi.district && e.poi.address && e.poi.location) {
      showSearchItem.value = true
      itemArr.value = [e.poi.name, e.poi.address, e.poi.location]
    }
  })
}
function typeSearch(type) {
  let placeSearch = new AMap.PlaceSearch({
    pageSize: 6, 
    pageIndex: 1, 
    city: `${localCity.value}`, 
    citylimit: true, 
    map: map, 
    panel: 'panel', 
  })
  let cpoint = mapCenter.value 
  placeSearch.searchNearBy(`${type}`, cpoint, 2000)
}
const handleType = (type) => {
  if (type == '0') {
    typeSearch('美食')
  } else if (type == '1') {
    typeSearch('酒店')
  } else if (type == '2') {
    typeSearch('景点')
  } else if (type == '3') {
    typeSearch('小区')
  }
  showPanel.value = true
}
const handleKeywordSearch = (keyword) => {
  typeSearch(`${keyword}`)
  showPanel.value = true
}

let driving = null
let transfer = null
let walking = null
const clearSearch = ()=>{
    if(walking){
      walking.clear()
    }
    if(driving){
      driving.clear()
    }
    if(transfer){
      transfer.clear()
    }
}
const handleGoingTo = (keyword) => {
  if (keyword[2] == '0') {
    ElMessage({
      message: '正在查询',
      type: 'info',
      duration: 500,
    })
    clearSearch()
    driving = new AMap.Driving({
      map: map,
      panel: 'panel-driving',
    })

    const points = [
      { keyword: `${keyword[0]}`, city: `${cityAdcode.value}` },
      { keyword: `${keyword[1]}`, city: `${cityAdcode.value}` },
    ]
    driving.search(points)
    changeShowPanelDrivingTrue()
  }
  if (keyword[2] == '1') {
    ElMessage({
      message: '正在查询',
      type: 'info',
      duration: 500,
    })
    clearSearch()
    const transOptions = {
      map: map,
      city: `${cityAdcode.value}`,
      panel: 'panel-driving',
    }
    transfer = new AMap.Transfer(transOptions)
    transfer.search([{ keyword: keyword[0] }, { keyword: keyword[1] }])
    changeShowPanelDrivingTrue()
    }
    
  
  if (keyword[2] == '2') {
    ElMessage({
      message: '正在查询',
      type: 'info',
      duration: 500,
    })
    clearSearch()
    walking = new AMap.Walking({
      map: map,
      panel: 'panel-driving',
    })
    walking.search([{ keyword: keyword[0] }, { keyword: keyword[1] }])
    changeShowPanelDrivingTrue()
  }
  }
  
const centerArea = ref({
  name: '',
  adcode: '' 
})

const handleSelectMap = (index) => {
  switch (index) {
    case 0:
      map.setMapStyle('amap://styles/normal')
      break
    case 1:
      map.setMapStyle('amap://styles/blue')
      break
    case 2:
      map.setMapStyle('amap://styles/dark')
      break
  }
}

onMounted(async () => {
  window._AMapSecurityConfig = {
    securityJsCode: 'cf47c9349a5fc4049a0f46db066857ae',
  }
  AMap = await AMapLoader.load({
    key: 'e0444ce967dce49da7ea110d4b3eac99',
    version: '2.0',
    plugins: [
      'AMap.Scale',
      'AMap.ControlBar',
      'AMap.ToolBar',
      'AMap.Geolocation',
      'AMap.CitySearch',
      'AMap.MouseTool',
      'AMap.AutoComplete',
      'AMap.PlaceSearch',
      'AMap.Geocoder',
      'AMap.Driving',
      'AMap.Transfer',
      'AMap.Walking',
    ],
  })
  map = new AMap.Map('container', {
    viewMode: '3D',
    center: [114.3, 30.5],
    zoom: 10,
  })
  useControls(map, AMap)
  const citySearch = new AMap.CitySearch()
  citySearch.getCityByIp('59.68.0.0', (status, result) => {
    if (status === 'complete' && result.info === 'OK') {
      let lngLat = result.rectangle.split(';').map((point) => {
        const [lng, lat] = point.split(',').map(Number)
        return { lng, lat }
      })
      let lng = lngLat.reduce((acc, cur) => acc + cur.lng, 0) / lngLat.length
      let lat = lngLat.reduce((acc, cur) => acc + cur.lat, 0) / lngLat.length
      localCity.value = result.city
      cityAdcode.value = result.adcode
      mapCenter.value = [lng, lat]
      map.setCenter([lng, lat])
    }
  })
  
  const geocoder = new AMap.Geocoder({
    radius: 1000,
    extensions: 'all'
  })

  map.on('moveend', updateCenterArea)
  map.on('zoomend', updateCenterArea)
  updateCenterArea()

  function updateCenterArea() {
    const center = map.getCenter()
    const zoom = map.getZoom() 


    geocoder.getAddress(center, (status, result) => {
      if (status === 'complete' && result.info === 'OK') {
        const addressComponent = result.regeocode.addressComponent
        let areaName, areaAdcode
      if (zoom > 10) {
        areaName = addressComponent.city || addressComponent.district || addressComponent.township
        areaAdcode = addressComponent.citycode || addressComponent.adcode
      } else if (zoom > 8) {
        areaName = addressComponent.province
        areaAdcode = addressComponent.adcode ? addressComponent.adcode.slice(0, 2) + '0000' : ''
      } else {
        areaName = addressComponent.country || '中国'
        areaAdcode = '100000'
      }

        if (centerArea.value.adcode !== areaAdcode) {
          centerArea.value = { name: areaName, adcode: areaAdcode }
          fetchWeather(areaAdcode)
        }
      }
    })
  }

  const fetchWeather = async (adcode) => {
    try {
      const res = await axios.get(
        `https://restapi.amap.com/v3/weather/weatherInfo?city=${adcode}&key=b246d3d6954ef868e6b9af454d7ad5c2&extensions=all`
      )
      const { nighttemp, daytemp, dayweather } = res.data.forecasts[0].casts[0]
      localLemplete.value = [daytemp, nighttemp, dayweather]
      localCity.value = centerArea.value.name
    } catch (err) {
      console.error('天气请求失败：', err)
    }
  }

})

</script>

<style lang="scss">
@import '//at.alicdn.com/t/c/font_4946657_x5pf4ygpc2.css';
.amap-controlbar {
  transform: scale(0.7);
}
.container {
  position: relative;
  z-index: 99;
  .closefullscreen {
    position: absolute;
    top: -50px;
    right: 50px;
    transition: all 0.1s ease;
    opacity: 0;
    button {
      width: 80px;
      height: 40px;
      background: #fff;
      border: none;
      outline: none;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
      color: #666;
      &:hover {
        color: #999;
      }
    }
    &.show {
      top: 70px;
      opacity: 1;
    }
  }
  
}

.marker-content {
  padding: 15px 10px;
  font-size: 14px;
  color: #666;
  display: flex;
  gap: 20px;
  .content-item {
    color: rgba(68, 234, 71, 0.639);
  }
}

.amap-sug-result {
  width: 345px;
  transform: translateX(-55px) translateY(3px);
  box-shadow: 0 0px 1px rgba(0, 0, 0, 0.3);
  .auto-item {
    color: #333;
    margin: 5px 0;
    &:hover {
      background: #eee;
    }
  }
}

#panel {
  position: fixed;
  background-color: white;
  overflow-y: auto;
  top: 300px;
  left: 10px;
  width: 350px;
  border-bottom: solid 1px silver;
  transition: all 0.7s ease-in-out;
  max-height: 0px;
  opacity: 0;
  pointer-events: none;
  &.showpanel {
    max-height: 550px;
    opacity: 1;
    pointer-events: auto;
  }
}
#panel-driving {
  position: fixed;
  background-color: white;
  overflow-y: auto;
  top: 100px;
  right: 10px;
  width: 300px;
  border-bottom: solid 1px silver;
  transition: all 0.7s ease-in-out;
  max-height: 0px;
  opacity: 0;
  pointer-events: none;
  z-index: 300;
  &.showpanel {
    max-height: 550px;
    opacity: 1;
    pointer-events: auto;
  }
}


</style>
